package com.cherish.pattern.proxy.dynamicproxy.myproxy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @Classname MyClassLoader
 * @Date 2019/4/2 20:57
 * @Author admin
 * @Description TODO
 */
public class MyClassLoader extends ClassLoader {

    private File classpathFile;

    public MyClassLoader() {
        String calsspath = MyClassLoader.class.getResource("").getPath();
        this.classpathFile = new File(calsspath);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = MyClassLoader.class.getPackage().getName() + "." + name;
        if (null != classpathFile) {
            File classFile = new File(classpathFile, name.replaceAll("\\.", "/") + ".class");
            if (classFile.exists()) {
                try {
                    FileInputStream inputStream = new FileInputStream(classFile);
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = inputStream.read(b)) != -1) {
                        outputStream.write(b, 0, len);
                    }
                    return defineClass(className, outputStream.toByteArray(), 0, outputStream.size());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
}
